package com.lin.linchatgpt.utils;

import com.unfbx.chatgpt.OpenAiClient;
import com.unfbx.chatgpt.OpenAiStreamClient;
import com.unfbx.chatgpt.interceptor.OpenAILogger;
import com.unfbx.chatgpt.interceptor.OpenAiResponseInterceptor;
import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;

import java.net.InetSocketAddress;
import java.net.Proxy;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * Copyright(C),2022年-2022,霖霖
 *
 * @author 霖霖
 * @version 1.0
 * @date 2023/4/3 21:51
 * @Description
 */
public class OpenAiClientUtil {
    public static OpenAiStreamClient getOpenAiStreamClientUtil(List<String> apiKeys){

        return OpenAiStreamClient.builder()
                .apiKey(apiKeys)
                .okHttpClient(getOkHttpClient())
                .build();
    }

    public static OkHttpClient getOkHttpClient(){
        Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("172.17.0.1", 7890));
        HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor(new OpenAILogger());
        //！！！！千万别再生产或者测试环境打开BODY级别日志！！！！
        //！！！生产或者测试环境建议设置为这三种级别：NONE,BASIC,HEADERS,！！！
        httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.HEADERS);
        return new OkHttpClient
                .Builder()
                .proxy(proxy)
//                .addInterceptor(httpLoggingInterceptor)
                .addInterceptor(new OpenAiResponseInterceptor())
                .connectTimeout(30, TimeUnit.SECONDS)
                .writeTimeout(30,TimeUnit.SECONDS)
                .readTimeout(30,TimeUnit.SECONDS)
                .build();
    }

    public static OpenAiClient getOpenAiClient(List<String> apiKeys){
        return OpenAiClient.builder()
                .apiKey(apiKeys)
                .okHttpClient(getOkHttpClient())
                .build();
    }
}
